package cn.cyh.queue_service.controller;

import cn.cyh.queue_service.common.Result;
import cn.cyh.queue_service.common.ResultCode;
import cn.cyh.queue_service.model.dto.PageRequest;
import cn.cyh.queue_service.model.dto.PageResult;
import cn.cyh.queue_service.model.entity.User;
import cn.cyh.queue_service.model.vo.UserVO;
import cn.cyh.queue_service.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/users")
@Tag(name = "用户管理", description = "用户管理相关接口")
@Slf4j
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;
    
    /**
     * 分页获取用户列表
     *
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param username 用户名（可选）
     * @param name 姓名（可选）
     * @param role 角色（可选）
     * @param status 状态（可选）
     * @return 用户列表分页结果
     */
    @GetMapping
    @Operation(summary = "分页获取用户列表", description = "分页获取用户列表，支持多种筛选条件")
    @PreAuthorize("hasAnyRole('ADMIN', 'SUPERADMIN')")
    public Result<PageResult<UserVO>> getUserList(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") int pageNum,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") int pageSize,
            @Parameter(description = "用户名") @RequestParam(required = false) String username,
            @Parameter(description = "姓名") @RequestParam(required = false) String name,
            @Parameter(description = "角色") @RequestParam(required = false) String role,
            @Parameter(description = "状态：0-禁用, 1-启用") @RequestParam(required = false) Integer status) {
        
        log.info("获取用户列表: pageNum={}, pageSize={}", pageNum, pageSize);
        
        PageRequest pageRequest = new PageRequest(pageNum, pageSize);
        pageRequest.addFilter("username", username);
        pageRequest.addFilter("name", name);
        pageRequest.addFilter("role", role);
        pageRequest.addFilter("status", status);
        
        PageResult<UserVO> pageResult = userService.getUserList(pageRequest);
        return Result.success(pageResult);
    }
    
    /**
     * 根据ID获取用户详情
     *
     * @param userId 用户ID
     * @return 用户详情
     */
    @GetMapping("/{userId}")
    @Operation(summary = "获取用户详情", description = "根据用户ID获取用户详情")
    @PreAuthorize("hasAnyRole('ADMIN', 'SUPERADMIN')")
    public Result<UserVO> getUserById(@Parameter(description = "用户ID") @PathVariable Long userId) {
        log.info("获取用户详情: userId={}", userId);
        UserVO userVO = userService.getUserById(userId);
        return Result.success(userVO);
    }
    
    /**
     * 更新用户信息
     *
     * @param userId 用户ID
     * @param user 用户信息
     * @return 更新结果
     */
    @PutMapping("/{userId}")
    @Operation(summary = "更新用户信息", description = "根据用户ID更新用户信息")
    @PreAuthorize("hasAnyRole('ADMIN', 'SUPERADMIN')")
    public Result<Boolean> updateUser(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @RequestBody User user) {
        
        log.info("更新用户信息: userId={}", userId);
        boolean result = userService.updateUser(userId, user);
        return Result.success(result);
    }
    
    /**
     * 删除用户
     *
     * @param userId 用户ID
     * @return 删除结果
     */
    @DeleteMapping("/{userId}")
    @Operation(summary = "删除用户", description = "根据用户ID删除用户")
    @PreAuthorize("hasRole('SUPERADMIN')")
    public Result<Boolean> deleteUser(@Parameter(description = "用户ID") @PathVariable Long userId) {
        log.info("删除用户: userId={}", userId);
        boolean result = userService.deleteUser(userId);
        return Result.success(result);
    }
    
    /**
     * 更新用户状态
     *
     * @param userId 用户ID
     * @param status 状态
     * @return 更新结果
     */
    @PutMapping("/{userId}/status")
    @Operation(summary = "更新用户状态", description = "根据用户ID更新用户状态")
    @PreAuthorize("hasAnyRole('ADMIN', 'SUPERADMIN')")
    public Result<Boolean> updateStatus(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "状态：0-禁用, 1-启用") @RequestParam Integer status) {
        
        log.info("更新用户状态: userId={}, status={}", userId, status);
        
        if (status != 0 && status != 1) {
            return Result.failed(ResultCode.PARAM_ERROR, "状态值只能为0或1");
        }
        
        boolean result = userService.updateStatus(userId, status);
        return Result.success(result);
    }
    
    /**
     * 重置用户密码
     *
     * @param userId 用户ID
     * @param newPassword 新密码
     * @return 重置结果
     */
    @PutMapping("/{userId}/password")
    @Operation(summary = "重置用户密码", description = "根据用户ID重置用户密码")
    @PreAuthorize("hasAnyRole('ADMIN', 'SUPERADMIN')")
    public Result<Boolean> resetPassword(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "新密码") @RequestParam String newPassword) {
        
        log.info("重置用户密码: userId={}", userId);
        boolean result = userService.resetPassword(userId, newPassword);
        return Result.success(result);
    }
} 